package cc.lj.internal.mobilepay.application.service;

import cc.lj.internal.core.exception.ServiceException;
import cc.lj.internal.mobilepay.domain.model.vo.CiticLogDO;
import cc.lj.internal.mobilepay.infrastructure.excepion.MobilepayExceptionEnum;
import cc.lj.internal.mobilepay.interfaces.dto.command.ReverseCommand;
import lj.internal.dict.enums.EnumCiticApiType;
import lj.internal.dict.enums.EnumCiticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一撤销订单 app service
 * @author liangxifeng
 * @date 2022/11/27 15:38
 */
@Service
@Slf4j
public class ReverseAppService extends CiticAppService<ReverseCommand,Boolean> {

    /**
     *
     * 1.从外部接收的参数
     * 2.新增中信日志表数据
     * 3. 调用中信统一撤销接口
     * 4. 将响应日志修改到数据中
     * @param command
     * @return true:撤销成功
     */
    @Override
    public Boolean doMain(ReverseCommand command) {
        Map<String,String> reqMap = new HashMap<>();
        //1.从外部接收的参数
        reqMap.put("out_trade_no",command.getOutTradeNo()); //商户订单号
        //该接口其他必要参数
        reqMap.put("service", EnumCiticService.REVERSE.getCode());//交易类型
        reqMap.put("mch_id", ljConfig.getMchId()); //商户号

        /**
         * 2.新增中信日志表数据
         */
        CiticLogDO addLogDO = new CiticLogDO();
        addLogDO.setApiType(EnumCiticApiType.REVERSE.getCode()); //接口类型
        Integer lastId = citicLog.addLog(command,reqMap,addLogDO);

        /**
         * 3. 调用中信统一撤销接口
         */
        Map<String, String> resMap = reuqestCitic.request(reqMap);

        /**
         * 4. 将响应日志修改到数据中
         */
        CiticLogDO updateLogDo = new CiticLogDO();
        citicLog.updateLog(lastId,resMap,updateLogDo);

        //通信状态
        boolean returnCodeBool = resMap.get("return_code") != null && resMap.get("return_code").equalsIgnoreCase("SUCCESS");
        //业务状态
        boolean resultCodeBool = resMap.get("result_code") != null && resMap.get("result_code").equalsIgnoreCase("SUCCESS");
        //boolean resultRes = resMap.get("return_code") != null && resMap.get("return_code").equalsIgnoreCase("SUCCESS")  && resMap.get("result_code ") != null && resMap.get("result_code").equalsIgnoreCase("SUCCESS");
        boolean resultRes = returnCodeBool && resultCodeBool;
        resMap.remove("sign"); //签名信息太长，可读性太差，这里删除掉了
        //通信状态和业务结果都为 SUCCESS
        if( resultRes ) {
            log.info("pact_id:"+command.getPactId()+",商户订单号:"+command.getOutTradeNo()+",撤销订单成功，结果map="+resMap);
            return true;
        } else {
            log.error("pact_id:"+command.getPactId()+",商户订单号:"+command.getOutTradeNo()+",撤销订单失败，结果map="+resMap);
            //接口调用失败
            throw new ServiceException(MobilepayExceptionEnum.CITIC_RESVERSE_FAILED,resMap.toString());
        }
    }
}
